from ctypes import *
from ..cpmem.ftco import FTMem
from .tools import suffix
class rx(FTMem):
    def __init__(self,config,rx_port_id=0):
        self.config  = config
        self.rx_port = rx_port_id
        fn = self.config.c_lib_dir + "libftcommap" + suffix()
        FTMem.__init__(self,fn)
        self.lib.init_rtldriver.restype = c_void_p

        memfn = "rx_rtl.{}".format(self.rx_port)
        self.h = self.lib.attachMem(memfn.encode(encoding="utf-8"))
    
    def open_driver(self):
        self.driver = self.lib.init_rtldriver(self.rx_port)
        self.lib.open_rtldriver(c_void_p(self.driver))
        self.lib.start_rtldriver(c_void_p(self.driver))
        self.suspend_driver()

    def init_driver(self,fc=874.2e6,gain=40.0,sr=1.92e6):
        if not hasattr(self, 'driver'):
            self.open_driver()
        else:
            self.resume_driver()
        self.set_rx_freq(fc)
        self.set_rx_gain(gain)
        self.set_rx_sr(sr)

    def start_driver(self):
        self.resume_driver()

    def suspend_driver(self):
        if hasattr(self, 'driver'):
            self.lib.suspend_rtldriver(c_void_p(self.driver))

    def resume_driver(self):
        if hasattr(self, 'driver'):
            self.lib.resume_rtldriver(c_void_p(self.driver))
        else:
            self.driver = self.lib.init_rtldriver(self.rx_port)
            self.lib.open_rtldriver(c_void_p(self.driver))
            
    def ls_driver(self):
        c = self.lib.get_device_count()
        manufact = (c_ubyte * 256)()
        product  = (c_ubyte * 256)()
        serial   = (c_ubyte * 256)()
        res = []
        toStr = lambda bfr:''.join((chr(b) for b in bfr if b > 0))
        for i in range(c):
            r = self.lib.get_usb_strings(c_uint32(i), manufact, product, serial)
            if r != 0:
                print('while reading USB strings (device %d)' % (i))
            res.append({"manufact":toStr(manufact),"product":toStr(product),"serial":toStr(serial)})
        return res

    def set_rx_freq(self,f):
        self.fc = f
        self.lib.set_frequency_rtldriver(c_void_p(self.driver),c_uint32(int(self.fc)))
        
    def get_rx_freq(self):
        return self.fc

    def set_rx_gain(self,g):
        self.gain = g
        iGain = int(self.gain*10)
        self.lib.gain_set_rtldriver(c_void_p(self.driver),c_uint32(iGain))
        
    def get_rx_gain(self):
        return self.gain

    def set_rx_sr(self,sr):
        self.sr = sr
        self.lib.set_sample_rate_rtldriver(c_void_p(self.driver),c_uint32(int(self.sr)))
        
    def get_rx_sr(self):
        return self.sr

        

        
